package context

import (
	"encoding/json"
	"errors"
	errors2 "gitee.com/go-web-2/web_framework/errors"
	template2 "gitee.com/go-web-2/web_framework/template/engine"
	"log"
	"net/http"
)

type Context struct {
	W             http.ResponseWriter
	R             *http.Request
	RouteParams   map[string]string
	RouteDynamic  string
	Engine        template2.Engine
	MatchRoute    string
	RespStatus    int
	RespData      []byte
	SkipFlashResp bool
}

func (c *Context) RespNotFound() {
	res := &Response{
		Status:  StatusErr,
		Message: errors2.RouteNotFound.Error(),
	}
	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.RespStatus = http.StatusNotFound
	c.RespData = bs
}

func (c *Context) RespBusinessErr(message string) {
	res := &Response{
		Status:  StatusErr,
		Message: message,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.RespStatus = http.StatusOK
	c.RespData = bs
}

func (c *Context) RespOk(data any) {
	res := &Response{
		Status: StatusOk,
		Data:   data,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.RespStatus = http.StatusOK
	c.RespData = bs
}

func (c *Context) RespBadRequest(message string) {
	res := &Response{
		Status:  StatusErr,
		Message: message,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.RespStatus = http.StatusBadRequest
	c.RespData = bs
}

func (c *Context) RespUnauthorized(message string) {
	res := &Response{
		Status:  StatusErr,
		Message: message,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.RespStatus = http.StatusUnauthorized
	c.RespData = bs
}

func (c *Context) RespUnauthorizedDirect(message string) {
	res := &Response{
		Status:  StatusErr,
		Message: message,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		c.RespSystemErr(errors2.ServerError.Error())
		return
	}

	c.W.WriteHeader(http.StatusUnauthorized)
	_, _ = c.W.Write(bs)
}

func (c *Context) RespSystemErr(message string) {
	res := &Response{
		Status:  StatusErr,
		Message: message,
	}

	bs, err := json.Marshal(res)
	if err != nil {
		log.Println(err)
		return
	}

	c.RespStatus = http.StatusInternalServerError
	c.RespData = bs
}

func (c *Context) Reset(w http.ResponseWriter, r *http.Request) {
	c.W = w
	c.R = r
	c.SkipFlashResp = false
	c.RouteParams = make(map[string]string)
}

func (c *Context) Render(tplName string, data interface{}) ([]byte, error) {
	if c.Engine == nil {
		return nil, errors.New("engine is nil")
	}
	return c.Engine.Render(tplName, data)
}
